package com.davidlife.services.objserialization;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 基于Hessian的对象序列化
 * 效率比Google的Protocal Buffers稍低，比Java内置的高很多。性能稳定，对各种编程语言有着良好的支持
 * 需要引入第三方包：hessian-4.0.7.jar
 */
public class HessianSerialization {
    public static void main(String[] args) throws IOException {
        String str = "abc";
        byte[] bytes = serializeObj(str);
        System.out.println(bytes);
        String str2 = (String) deserializeObj(bytes);
        System.out.println(str2);

    }

    public static byte[] serializeObj(Object obj) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HessianOutput out = new HessianOutput(bos);
        out.writeObject(obj);
        byte[] bytes = bos.toByteArray();
        return bytes;
    }

    public static Object deserializeObj(byte[] bytes) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        HessianInput in = new HessianInput(bis);
        Object obj = in.readObject();
        return obj;
    }
}
